package indi.wshape1.takeawaydeliveryinfo.servlet;

import indi.wshape1.takeawaydeliveryinfo.service.UtilService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Wshape1
 * @create 2022-11-13 19:05
 */

@WebServlet(name = "OnloadServlet", value = {"/onload"})
public class OnloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();

        HttpSession session = req.getSession();

        if (session.getAttribute("user") != null) {
            writer.print(1);
            return;
        }

        Cookie[] cookies = req.getCookies();
        for (Cookie co : cookies) {
            if ("noLogin".equals(co.getName())) {
                String[] value = co.getValue().split(":"); // 0 - type  1 - user    2 - pwd
                if (value.length == 3) {
                    //  如果 已在异地登录
                    if (req.getServletContext().getAttribute(value[1]) != null) {
//                        删除本地cookie
                        co.setMaxAge(0);
                        co.setPath("/");
                        resp.addCookie(co);
                        writer.print(0);
                        return;
                    }
                    boolean isLogin = false;
                    if ("sender".equals(value[0]) && UtilService.loginSender(value[1], value[2])) {
                        isLogin = true;
                    } else if ("admin".equals(value[0]) && UtilService.loginAdmin(value[1], value[2])) {
                        isLogin = true;
                    } else if ("root".equals(value[0]) && UtilService.loginRoot(value[1], value[2])) {
                        isLogin = true;
                    }

                    if (isLogin) {
                        req.getServletContext().setAttribute(value[1], value[0]);
                        req.getSession().setAttribute("user", value[1]);
                        writer.print(1);
                        return;
                    }

                }
                break;
            }
        }

        writer.print(0);
    }
}
